import React, { useState, useEffect, useRef, useCallback } from 'react';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { produce, setAutoFreeze } from 'immer'
import Markdown from './markdown';
import myFetch from './fetch';

const Chat = () => {
  const [replyText, setReplyText] = useState('');
  const [messageList, setMessageList] = useState([]);
  const [loading, setLoading] = useState(true);
  const ctrl = useRef(new AbortController());
  const messageEnd = useRef(false);
  const [chatList, setChatList] = useState([]);
  const chatListRef = useRef([]);
  const textRef = useRef('');
  const conversationId = useRef('')
  const taskIdRef = useRef('')

  const onCompleted = () => {
    console.log('completed');
  };
  const onMessageEnd = () => {
    console.log('message end');
  };

  const handleUpdateChatList = useCallback((newChatList) => {
    setChatList(newChatList)
    chatListRef.current = newChatList
  }, [])

  const updateCurrentQA = useCallback(({
    responseItem,
    questionId,
    placeholderAnswerId,
    questionItem,
  }) => {
    const newListWithAnswer = produce(
      chatListRef.current.filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
      (draft) => {
        if (!draft.find(item => item.id === questionId))
          draft.push({ ...questionItem })

        draft.push({ ...responseItem })
      })
    handleUpdateChatList(newListWithAnswer)
  }, [handleUpdateChatList])

  const onSend = () => {
    const questionId = `question-${Date.now()}`
    const questionItem = {
      id: questionId,
      content: '',
      isAnswer: false,
      message_files: null,
    }

    const placeholderAnswerId = `answer-placeholder-${Date.now()}`
    const placeholderAnswerItem = {
      id: placeholderAnswerId,
      content: '',
      isAnswer: true,
    }

    const newList = [...chatListRef.current, questionItem, placeholderAnswerItem]
    handleUpdateChatList(newList)

    const responseItem = {
      id: placeholderAnswerId,
      content: '',
      agent_thoughts: [],
      message_files: [],
      isAnswer: true,
    }

    let isAgentMode = false
    let hasSetResponseId = false



    const onData = (message, isFirstMessage, { conversationId: newConversationId, messageId, taskId }) => {
      if (!isAgentMode) {
        responseItem.content = responseItem.content + message
      }
      else {
        const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
        if (lastThought)
          lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
      }
      if (messageId && !hasSetResponseId) {
        responseItem.id = messageId
        hasSetResponseId = true
      }
      if (isFirstMessage && newConversationId)
        conversationId.current = newConversationId
      
      taskIdRef.current = taskId
      if (messageId)
        responseItem.id = messageId

      updateCurrentQA({
        responseItem,
        questionId,
        placeholderAnswerId,
        questionItem,
      })
  


      // textRef.current += message;
      // setReplyText(textRef.current);
    };

    myFetch(onData, onCompleted, onMessageEnd)
  }

  useEffect(() => {
    
  }, []);
  
  return (
    <div>
      <h1 onClick={onSend}>Chat</h1>
      <p>Chat component</p>
      {/* <Markdown content={replyText}></Markdown> */}
      {
        chatList.map(item => {
          return (
            <Markdown content={item.content}></Markdown>
          )
        })
      }
    </div>
  );
};

export default Chat;